"""
增值税发票Excel导入导出工具
基于tax_template.xlsx模板实现单张增值税专用发票的导出
"""
import os
from openpyxl import load_workbook
from openpyxl.styles import Alignment
from datetime import datetime


class VATInvoiceExporter:
    """增值税专用发票导出器"""
    
    def __init__(self, template_path=None):
        """
        初始化导出器
        :param template_path: 模板文件路径，默认使用common/tax_template.xlsx
        """
        if template_path is None:
            current_dir = os.path.dirname(os.path.abspath(__file__))
            template_path = os.path.join(current_dir, 'tax_template.xlsx')
        self.template_path = template_path
    
    def export_invoice(self, invoice_data, output_path):
        """
        导出单张增值税专用发票到Excel
        
        :param invoice_data: 发票数据字典，包含以下字段：
            - invoice_code: 发票代码
            - invoice_number: 发票号码
            - invoice_date: 开票日期
            - buyer_name: 购买方名称
            - buyer_tax_id: 购买方识别号
            - buyer_address_phone: 购买方地址电话
            - buyer_bank_account: 购买方开户行及账号
            - seller_name: 销售方名称
            - seller_tax_id: 销售方识别号
            - seller_address_phone: 销售方地址电话
            - seller_bank_account: 销售方开户行及账号
            - items: 商品明细列表，每项包含：
                - name: 项目名称
                - spec: 规格型号
                - unit: 单位
                - quantity: 数量
                - price: 单价
                - amount: 金额
                - tax_rate: 税率
                - tax: 税额
            - total_amount: 合计金额
            - total_tax: 合计税额
            - password_area: 密码区（可选）
        :param output_path: 输出文件路径
        :return: 成功返回True，失败抛出异常
        """
        # 加载模板
        wb = load_workbook(self.template_path)
        ws = wb.active
        
        # 填充发票基本信息（B2:H2, B3:H3, B4:H4 是合并单元格，填充起始单元格B列）
        ws['B2'] = invoice_data.get('invoice_code', '')  # 发票代码
        ws['B3'] = invoice_data.get('invoice_number', '')  # 发票号码
        ws['B4'] = invoice_data.get('invoice_date', '')  # 开票日期
        
        # 填充购买方信息（C5:D5等是合并单元格，填充起始单元格C列）
        ws['C5'] = invoice_data.get('buyer_name', '')  # 购买方名称
        ws['C6'] = invoice_data.get('buyer_tax_id', '')  # 购买方识别号
        ws['C7'] = invoice_data.get('buyer_address_phone', '')  # 购买方地址电话
        ws['C8'] = invoice_data.get('buyer_bank_account', '')  # 购买方开户行及账号
        
        # 填充密码区（F5:H8是合并单元格，填充起始单元格F5）
        if invoice_data.get('password_area'):
            ws['F5'] = invoice_data.get('password_area', '')
        
        # 填充商品明细（从第10行开始）
        items = invoice_data.get('items', [])
        start_row = 10
        for idx, item in enumerate(items):
            row = start_row + idx
            ws[f'A{row}'] = item.get('name', '')  # 项目名称
            ws[f'B{row}'] = item.get('spec', '')  # 规格型号
            ws[f'C{row}'] = item.get('unit', '')  # 单位
            ws[f'D{row}'] = item.get('quantity', '')  # 数量
            ws[f'E{row}'] = item.get('price', '')  # 单价
            ws[f'F{row}'] = item.get('amount', '')  # 金额
            ws[f'G{row}'] = item.get('tax_rate', '')  # 税率
            ws[f'H{row}'] = item.get('tax', '')  # 税额
        
        # 填充合计信息（A13:D13, A14:D14是合并单元格，金额填在F列）
        ws['F13'] = invoice_data.get('total_amount', '')  # 合计金额
        ws['F14'] = invoice_data.get('total_tax', '')  # 合计税额
        
        # 填充销售方信息
        ws['C15'] = invoice_data.get('seller_name', '')  # 销售方名称
        ws['C16'] = invoice_data.get('seller_tax_id', '')  # 销售方识别号
        ws['C17'] = invoice_data.get('seller_address_phone', '')  # 销售方地址电话
        ws['C18'] = invoice_data.get('seller_bank_account', '')  # 销售方开户行及账号
        
        # 保存文件
        wb.save(output_path)
        return True


def export_vat_invoice(invoice_data, output_path, template_path=None):
    """
    快捷导出增值税专用发票方法
    
    :param invoice_data: 发票数据字典
    :param output_path: 输出文件路径
    :param template_path: 模板文件路径（可选）
    :return: 成功返回True
    """
    exporter = VATInvoiceExporter(template_path)
    return exporter.export_invoice(invoice_data, output_path)
